<template>
	<!-- 预览组件 -->
	<view class="preview" :style="`display: ${previewb?'block':'none'};padding-top:${navTop + biasTop}px`"
		@click="closeFn">
		<!-- 当前页/总页数 -->
		<view class="p-pages" :style="`top:${navTop + biasTop}px`">{{pageNumber}}/{{staticSrc.length}}</view>
		<swiper class="p-swiper" :style="` height:calc(100% - 100rpx - env(safe-area-inset-bottom))`"
			:current="pageNumber<=staticSrc.length?pageNumber-1:0" :circular="true" @change="changeFn"
			:duration="animationb?200:0">
			<swiper-item class="item" v-for="(item,index) in staticSrc" :key="index">
				<video :src="item.value" :enable-progress-gesture="false" :show-mute-btn="true" class="p-media"
					@longpress="saveVideoFn(item.value)" @click.stop v-if="item.type=='video'" :id="`video_${index}`"
					:enable-play-gesture="true"></video>
				<image :src="item.value" mode="widthFix" class="p-media" v-else @click.stop
					:show-menu-by-longpress="true"></image>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	let app = getApp();
	// currentIndex多个媒体格式预览必传,传过来的index一般要+1
	// staticSrc内数据多个，表示多个媒体文件预览，必传
	// previewb预览弹窗开关，必传
	export default {
		name: "previewMedia",
		props: {
			// staticSrc格式：[{type:image,value:scr},{type:video,value:src}]
			staticSrc: {
				type: Array,
				default: []
			},
			previewb: {
				type: Boolean,
				default: false
			},
			currentIndex: {
				type: Number,
				default: -1
			}
		},
		data() {
			return {
				pageNumber: 1,
				navTop: app.globalData.navTop,
				animationb: true,
				platForm: app.globalData.platForm,
				biasTop: 0,
			};
		},
		mounted() {
			// 平台切换
			if (this.platForm == 'mp-weixin') {
				this.biasTop = app.globalData.biasTop_88 //顶部偏差
			}
		},
		methods: {
			closeFn() {
				this.$emit('previewClose', false);
				for (let i = 0; i < this.staticSrc.length; i++) { //视频暂停
					let item = this.staticSrc[i];
					if (item.type == 'video') {
						let operate = uni.createVideoContext(`video_${i}`);
						operate.pause(); //暂停播放
					}
				}
			},
			changeFn(e) {
				let index = e.detail.current;
				this.pageNumber = index + 1;
				for (let i = 0; i < this.staticSrc.length; i++) { //视频暂停
					let item = this.staticSrc[i];
					if (item.type == 'video' && index != i) {
						let operate = uni.createVideoContext(`video_${i}`);
						operate.pause(); //暂停播放
					}
				}
			},
			//保存视频
			saveVideoFn(url) {
				// 提醒用户下载中
				uni.showModal({
					title: _this.platForm == 'web' ? '是否下载视频？' : '是否将视频保存到相册？',
					content: _this.platForm == 'web' ? '此操作需要在浏览器内才能执行，如不在浏览器内请先打开浏览器' : '',
					success: res => {
						if (res.confirm) {
							if (_this.platForm == 'web') { //H5
								_this.webVideo(url, function() {
									uni.showToast({
										title: "保存成功",
										icon: "success"
									});
								});
							} else {
								uni.authorize({ //授权
									scope: 'scope.writePhotosAlbum',
									success: res => {
										_this.upVideo(url);
									},
									fail: res => {
										uni.showToast({
											title: "保存失败，相册存储权限获取失败",
											icon: "fail"
										});
									}
								})
							}
						}
					}
				})
			},
			upVideo(url) {
				uni.downloadFile({
					url: url,
					success: (res) => {
						// 2 成功下载后而且状态码为200时将视频保存到本地系统
						if (res.statusCode === 200) {
							uni.saveVideoToPhotosAlbum({
								filePath: res.tempFilePath,
								success: res => {
									// 提示用户下载成功
									uni.showToast({
										title: "保存成功",
										icon: "success"
									});
								},
								fail: res => {
									uni.showToast({
										title: "保存失败，请刷新页面重试",
										icon: "error"
									});
								}
							})
						}
						// 如果该资源不可下载或文件格式出错则提示用户
						else {
							uni.showToast({
								title: "保存失败，请刷新页面重试",
								icon: "error"
							});
						}
					},
					fail: (err) => {
						// 下载失败提醒
						uni.showToast({
							title: "保存失败，请刷新页面重试",
							icon: "error"
						})
					}
				})
			},
			webVideo(url, success) {
				uni.showLoading({
					title: '下载中'
				})
				var xhr = new XMLHttpRequest();
				xhr.open('GET', url, true);
				xhr.responseType = 'blob';
				xhr.onload = function() {
					if (xhr.readyState === 4 && xhr.status === 200) {
						const blob = new Blob([this.response], {
							type: 'video/mp4'
						});
						const a = document.createElement("a"); //创建a标签
						a.href = window.URL.createObjectURL(blob); // 创建下载的链接
						a.download = 'video'; //下载文件名称
						a.style.display = "none";
						document.body.appendChild(a); //a标签追加元素到body内
						a.click(); //模拟点击下载
						document.body.removeChild(a); // 下载完成移除元素
						window.URL.revokeObjectURL(a.href); // 释放掉blob对象
						uni.hideLoading();
						success(); //运行回调
					}
				}
				xhr.send();
			}
		},
		watch: {
			currentIndex(newvalue, oldvalue) {
				this.pageNumber = newvalue;
				this.animationb = false;
				setTimeout(res => {
					this.animationb = true;
				}, 0)
			}
		}
	}
</script>

<style>
	@import url("./previewMedia.css");
</style>